package com.example.demo.shiro;

import com.example.demo.bean.User;
import com.example.demo.serivce.StudentService;
import com.example.demo.serivce.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     *
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权逻辑");
        return null;
    }

    /**
     *
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        Map<String,Object> map = new HashMap<String, Object>(1);

        map.put("username",token.getUsername());

        List<User> listUser = userService.selectUser(map);

        System.out.println("认证逻辑");

        if (listUser.size() == 0) {
            //若执行此步操作，控制层会抛空指针异常AuthenticationException
            System.out.println("用户名不存在");

            return null;
        } else {

            System.out.println("密码验证");

            return new SimpleAuthenticationInfo("",listUser.get(0).getPassword(),"");
        }

    }
}
